<?php
/**
* user.php
*
* Create on 2016-11-18
* Create by TT
*/
namespace haibao\cms\business\nh;

use \haibao\cms\data\nh\User as UserData;
use \haibao\cms\model\filter\nh\Lottery as LotteryFilter;
use \haibao\cms\model\filter\nh\Card as  CardFilter;
use \haibao\cms\model\filter\nh\Photo as PhotoFilter;
use haibao\cms\web\view\test\Card;
use haibao\frame\data\query\Condition;
class User {
	
	/**
	 * 添加微信用户绑定
	 * @param \haibao\cms\model\data\nh\User $model
	 * @throws \haibao\cms\business\BusinessException
	 */
	const VOTE_RATE = 80;
	public static function addUserModel($model,$isCheck = true,$isSendCard = true){
		if($isCheck){
			self::checkData($model);
			
			$userName = self::getUserNameByMobile($model->Mobile);
			if(empty($userName)){
				throw new \haibao\cms\business\BusinessException('对不起，此手机不属性海报员工，请修改手机号');
			}
			$model->Name = $userName;
		}
		
		$userModel = self::getUserByOpenId($model->OpenId);
		if($userModel){
			throw new \haibao\cms\business\BusinessException('微信ID已经绑定其它账号');
		}

		$model->PhotoUrl = '';
		$model->IsWin = 0;
		$model->Status = \haibao\cms\model\data\nh\User::STATUS_TYPE_OPEN;
		$model->CreateTime = new \DateTime();
		$model->PhotoCard = 0;
		$data = new UserData();
		if($isSendCard){
			$data->addModel($model);
		} else {
			$data->add($model);
		}
	}
	
	public static function getUserList($filter){
		$data = new UserData();
		return $data->getAll($filter);
	}
	
	/**
	 * 设置微信用户头像地址
	 * @param string $openId
	 * @param string $url
	 */
	public static function updateUserPhotoUrl($userId,$openId,$url){
		$data = new UserData();
		$data->updateUserPhotoUrl($userId,$openId, $url);
	}
	
	public static function closeUserById($openId){
		$data = new UserData();
		$data->closeUserById($openId);
	}
	
	/**
	 * 给用户发明星卡片
	 * @param array $userIds
	 * @param int $sendCount
	 */
	public static function sendCardToUser($userIds,$sendCount = 1,$isCache = false){
		$data = new UserData();
		return $data->sendCardToUser($userIds, $sendCount,$isCache);
	}
	
	/**
	 * 通过手机号得cms后台用户姓名
	 * @param unknown_type $mobile
	 */
	public static function getUserNameByMobile($mobile){
		$data = new UserData();
		return $data->getUserNameByMobile($mobile);
	}
	
	/**
	 * 通过微信openId得用户信息
	 * @param unknown_type $openId
	 */
	public static function getUserByOpenId($openId){
		$data = new UserData();
		return $data->getUserByOpenId($openId);
	}
	
	/**
	 * 用户微信上传图片
	 * @param haibao\cms\model\data\nh\Photo $model
	 * @param int $photoCard	得卡机率
	 * @throws Exception
	 */
	public static function addUserPhoto($openId,$model,$photoCard = 0){
		$data = new UserData();
		return $data->addPhotoModel($openId,$model,$photoCard);
	}
	
	public static function getSendPhotoSuccess($userId){
		$data = new UserData();
		return $data->getSendPhotoSuccess($userId);
	}
	
	public static function sendPhotoSuccess($userId){
		$data = new UserData();
		return $data->sendPhotoSuccess($userId);
	}
	
	/**
	 * 得用户微信上传图片列表
	 * @param unknown_type $filter
	 */
	public static function getUserPhoto($filter){
		$data = new UserData();
		return $data->getAll($filter);
	}
	
	public static function getUserPhotoCount($userId = 0){
		$data = new UserData();
		return $data->getUserPhotoCount($userId);
	}
	
	/**
	 * 删除用户微信上传的图片
	 * @param unknown_type $userId
	 * @param unknown_type $photoId
	 */
	public static function delUserPhoto($userId,$photoId){
		$data = new UserData();
		$data->delUserPhoto($userId,$photoId);
	}
	
	/**
	 * 用户转赠卡片
	 * @param unknown_type $userId
	 * @param unknown_type $cardIds
	 * @param unknown_type $toUserId
	 */
	public static function sendUserCard($userId,$cardIds,$toUserId){
		$data = new UserData();
		$data->sendUserCard($userId,$cardIds,$toUserId);
	}
	
	/**
	 * 给用户发微信消息
	 * @param haibao\cms\model\data\nh\Message/array() $model
	 */
	public static function addMessage($model){
		$data = new UserData();
		$data->addMessage($model);
	}
	
	public static function getLotteryList($isAll = false){

		$prevLotteryId = 0;
		$nhCache = new \haibao\cms\cache\nh();
		/* if(!$isAll){
			$prevLotteryId = $nhCache->getLotteryPrevId();
		} */
		$lotteryList = array();
		$lotteryFilter = new LotteryFilter();
		$lotteryFilter->select(array(
				LotteryFilter::CONDITION_FIELD_NAME_ID,
				LotteryFilter::CONDITION_FIELD_NAME_CARDID,
				LotteryFilter::CONDITION_FIELD_NAME_USERID,
		));
		$cardFilter = new CardFilter();
		$cardFilter->select(array(
				CardFilter::CONDITION_FIELD_NAME_NAME_CN,
				CardFilter::CONDITION_FIELD_NAME_TOPICID,
		));
		/* if($prevLotteryId){
			$lotteryFilter->where(LotteryFilter::CONDITION_FIELD_NAME_ID,Condition::CONDITION_GREATER,(int)$prevLotteryId);
		} */
		$lotteryFilter->innerJoin($cardFilter,null,LotteryFilter::CONDITION_FIELD_NAME_CARDID,$cardFilter::CONDITION_FIELD_NAME_ID,LotteryFilter::CONDITION_FIELD_NAME_CARDINFO,false);
		$data = new UserData();
		$result = $data->getAll($lotteryFilter);
		if($result){
			foreach($result as $list){
				array_push($lotteryList,array("cardId"=>$list->CardId,"player"=>$list->UserId,"topicId"=>$list->CardInfo->TopicId,"cardName"=>$list->CardInfo->Name_CN));
				$finalLotteryId = $list->Id;
			}
			$nhCache->setLotteryMaxId($finalLotteryId);
		}
		return $lotteryList;
	}
	
	public static function getUserCard($filter){
		$data = new UserData();
		return $data->getAll($filter);
	}
	
	public static function getUserCardByUserId($userId){
		$data = new UserData();
		return $data->getUserCardByUserId($userId);
	}
	
	/**
	 * 用户选择卡片进入抽奖池
	 * @param array(haibao\cms\model\data\nh\Lottery) $models
	 */
	public static function addLotteryList($models){
		$data = new UserData();
		$data->addLotteryList($models);
	}
	
	/**
	 * 清空抽奖池
	 */
	public static function delLottery($isSendCard = true){
		$data = new UserData();
		$data->delLottery($isSendCard);
	}
	
	public static function sendCardToAllUser(){
		$data = new UserData();
		$data->sendCardToAllUser();
	}
	
	/**
	 * 中奖用户
	 * @param array $userId
	 * @throws Exception
	 */
	public static function setUserWin($userIds){
		$data = new UserData();
		return $data->setUserWin($userIds);
	}
	
	/**
	 * 得当前流程位置
	 * @return number
	 */
	public static function getFlowType(){
		$data = new UserData();
		return $data->getFlowType();
	}
	
	/**
	 * 设置当前流程位置
	 * @return number
	 */
	public static function setFlowType($flowType){
		$data = new UserData();
		return $data->setFlowType($flowType);
	}
	
	/**
	 * 随机抽取没有参加抽奖用户的一张卡片进入抽奖池
	 */
	public static function drawoffUserCard(){
		$data = new UserData();
		$data->drawoffUserCard();
	}
	
	/**
	 * 得到参加抽卡用户缓存
	 *  @return array(userid)
	 */
	public static function getDrawCardCache(){
		$userCache = new \haibao\cms\cache\Nh();
		return $userCache->getDrawCard();
	}
	
	/**
	 * 设置参加抽卡用户缓存
	 * @param unknown_type $val
	 */
	public static function setDrawCardCache($userId){
		$userCache = new \haibao\cms\cache\Nh();
		$userIds = $userCache->getDrawCard();
		if($userIds){
			$userIds .= ','.$userId;
		} else {
			$userIds = $userId;
		}
		$userCache->setDrawCard($userIds);
	}
	
	/**
	 * 清除参加游戏用户缓存
	 */
	public static function delDrawCardCache(){
		$userCache = new \haibao\cms\cache\Nh();
		$userCache->delDrawCard();
	}
	
	public static function getVoteUserCache(){
		$userCache = new \haibao\cms\cache\Nh();
		return $userCache->getVoteUserCache();
	}
	
	public static function setVoteUserCache($userId){
		$userCache = new \haibao\cms\cache\Nh();
		$userIds = $userCache->getVoteUserCache();
		if($userIds){
			$userIds .= ','.$userId;
		} else {
			$userIds = $userId;
		}
		$userCache->setVoteUserCache($userIds);
	}
	
	public static function delVoteUserCache(){
		$userCache = new \haibao\cms\cache\Nh();
		$userCache->delVoteUserCache();
	}
	
	public static function getVoteList($voteRate = array(), $hasVote = false){

		$voteList = array(
			0=>array('title'=>'歌唱类','list'=>array(
				1 => array('title'=>'today','user'=>'陈艳','order'=>5,'num'=>self::getVoteCache('0_1')),
				2 => array('title'=>'你在终点等我','user'=>'汪圆','order'=>2,'num'=>self::getVoteCache('0_2')),
				3 => array('title'=>'We do not talk anymore','user'=>'罗一萱+陈佳','order'=>3,'num'=>self::getVoteCache('0_3')),
                4 => array('title'=>'歌曲串烧','user'=>'刘越','order'=>9,'num'=>self::getVoteCache('0_4')),
                5 => array('title'=>'催眠','user'=>'侯萍','order'=>12,'num'=>self::getVoteCache('0_5')),
                6 => array('title'=>'没你不行','user'=>'孙博文','order'=>7,'num'=>self::getVoteCache('0_6')),
                7 => array('title'=>'我们的歌','user'=>'周哲','order'=>15,'num'=>self::getVoteCache('0_7')),
                8 => array('title'=>'亲密爱人','user'=>'尤启越','order'=>13,'num'=>self::getVoteCache('0_8')),
			)),
			1=>array('title'=>'舞蹈类','list'=>array(
				1 => array('title'=>'西班牙斗牛舞','user'=>'销售+移动','order'=>1,'num'=>self::getVoteCache('1_1')),
				2 => array('title'=>'just dance','user'=>'郝磊','order'=>11,'num'=>self::getVoteCache('1_2')),
				3 => array('title'=>'how that taste','user'=>'靳悦','order'=>8,'num'=>self::getVoteCache('1_3')),
			)),
			2=>array('title'=>'表演类','list'=>array(
				1 => array('title'=>'韩剧太阳的后裔','user'=>'明星全组','order'=>6,'num'=>self::getVoteCache('2_1')),
				2 => array('title'=>'Amazing girl 经典女神×二次元男神','user'=>'美容全组','order'=>4,'num'=>self::getVoteCache('2_2')),
				3 => array('title'=>'外企员工','user'=>'王珺、李乐、徐畅彬、张翔宇、范珍珍','order'=>14,'num'=>self::getVoteCache('2_3')),
				4 => array('title'=>'疯狂动物城','user'=>'视频全组','order'=>10,'num'=>self::getVoteCache('2_4')),
			))

		);
		$arrIndex = 0;
		foreach($voteList as $category=>$list){
			foreach($list['list'] as $key=>$vote){
				
				if($hasVote){
					if(!$voteRate){
						$voteRate = array_pad(array(),15,0);
						$voteList[$category]['list'][$key]['num'] +=4;
						$voteRate[$arrIndex] += 4;
					}else{
						if($voteRate[$arrIndex]<=self::VOTE_RATE-1){
							$voteRate[$arrIndex] += 4;
							if($voteRate[$arrIndex] > self::VOTE_RATE){
								$voteRate[$arrIndex] = self::VOTE_RATE;
							}
						}else{
							$voteRate[$arrIndex] = self::VOTE_RATE;
						}
						$voteList[$category]['list'][$key]['num'] +=$voteRate[$arrIndex];
					}
					$arrIndex++;
				}
			}
			
			$categoryVoteNumArr = array_map('array_pop',$voteList[$category]['list']);
			$maxVoteNum = max($categoryVoteNumArr);
			$tempMaxKey = $tempMax = -1;
			foreach($categoryVoteNumArr as $key=>$num){
				if($maxVoteNum == $num){
					$voteList[$category]['leader'][] = array('title'=>$voteList[$category]['list'][$key]['title']);
				}else{
				    if($category == 0) {
                        if ($num > $tempMax) {
                            $tempMaxKey = $key;
                            $tempMax = $num;
                        }
                    }
                }
			}
            if($category == 0 && $tempMaxKey >0) {
                if (count($voteList[$category]['leader']) < 2) {
                    array_push($voteList[$category]['leader'], array('title' => $voteList[$category]['list'][$tempMaxKey]['title']));
                }
            }
		}
		return array($voteList,$voteRate);
	}
	
	public static function getVoteCache($voteId){
		$userCache = new \haibao\cms\cache\Nh();
		return $userCache->getVoteCache($voteId);
	}
	
	public static function setVoteCache($voteId,$num = 1){
		$userCache = new \haibao\cms\cache\Nh();
		$cacheNum = self::getVoteCache($voteId);
		if($cacheNum){
			$num += $cacheNum;
		}
		$userCache->setVoteCache($voteId,$num);
	}
	
	public static function delVoteCache(){
		$userCache = new \haibao\cms\cache\Nh();
		list($voteList,$voteRate) = self::getVoteList();
		foreach($voteList as $key=>$val){
			foreach($val['list'] as $k=>$v){
				$userCache->delVoteCache($key.'_'.$k);
			}
		}
	}
	
	/**
	 * 根据手机号查询用户
	 */
	public static function getUserByMobile($mobile){
		$data = new UserData();
		return $data->getUserByMobile($mobile);
	}
	
	/**
	 * 获取照片墙480 * 672
	 */
	public static function getPhotoWallList($prevId){

		$filter = new PhotoFilter();
		$filter->select(array(
				PhotoFilter::CONDITION_FIELD_NAME_ID,
				PhotoFilter::CONDITION_FIELD_NAME_PHOTOURL,
				PhotoFilter::CONDITION_FIELD_NAME_WIDTH,
				PhotoFilter::CONDITION_FIELD_NAME_HEIGHT,
		));
		if($prevId){
			$filter->where(PhotoFilter::CONDITION_FIELD_NAME_ID,Condition::CONDITION_GREATER,(int)$prevId);
		}
		$filter->where(PhotoFilter::CONDITION_FIELD_NAME_STATUS,Condition::CONDITION_EQUAL,\haibao\cms\model\data\nh\Photo::STATUS_TYPE_OPEN);
		$filter->limit(0,1);
		$data = new UserData();
		$photo = '';
		$result = $data->getOne($filter);
		if($result){
		    $width = $result->Width;
		    $height = $result->Height;
		    if($width > 480 && $height > 672){
                if($width > $height){
                    $width = floor($width*672/$height);
                    $height = 672;
                }elseif($height >= $width){
                    $height = floor($height*480/$width);
                    $width = 480;
                }
            }
            $photo = array('Id'=>$result->Id,'PhotoUrl'=>\haibao\cms\business\control\Base::getImageLink($result->PhotoUrl,$width,$height,75));

		$prevId = $result->Id;
		}else{
            $photo = $data->getRandomPhotoList();
		}
		return array($photo,$prevId);
		
	}
	
	public static function getRightUrlList($excludeUrl,$openId, $userId){
		$rightUrlList = array(
			'vote'=>\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_HOST_WAP).'/nh/vote.html?openid='.$openId.'&userid='.$userId,
			'photo'=>\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_HOST_WAP).'/nh/photo.html?openid='.$openId.'&userid='.$userId,
			'drawlottery'=>\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_HOST_WAP).'/nh/drawlottery.html?openid='.$openId.'&userid='.$userId,
		);
		unset($rightUrlList[$excludeUrl]);
		return $rightUrlList;
	}
	
	/**
	 * 获取明星墙图片
	 */
	public static function getStarWallList($query){
	    $nhStar = new \haibao\cms\data\nh\User();
	    return $nhStar->getStarWallList($query);
	}
	
	private static function checkData($userModel){
		if(empty($userModel->Mobile)) {
			throw new \haibao\cms\business\BusinessException('用户手机号不能为空');
		}
		if(empty($userModel->OpenId)) {
			throw new \haibao\cms\business\BusinessException('用户微信ID不能为空');
		}
	}
}